<template>
  <div id="login-regist">
    <button class="close-login-regist" @click="closeLoginRegist">×</button>
    <div class="toggle-login-regist" ref="toggleBtn">
      <button @click="showLoginForm">登录</button>&emsp;|&emsp;
      <button @click="showRegistForm">注册</button>
    </div>
    <div class="login-form" v-if="isLoginForm">
      <label for="login-account">
        帐号：
        <input type="text" id="login-account" v-model="loginAccount" />
      </label>
      <br />
      <label for="login-pwd" class="login-pwd">
        密码：
        <input :type="isLoginPwdShow ? 'text' : 'password'" id="login-pwd" v-model="loginPwd" />
        <button
          class="toggle-show"
          v-if="loginPwd.length > 0"
          @click="isLoginPwdShow = !isLoginPwdShow"
        >{{isLoginPwdShow ? '隐藏' : '显示'}}</button>
      </label>
      <br />
      <div class="login-submit-btn">
        <button @click="login">登录</button>
      </div>
    </div>
    <div class="regist-form" v-if="isRegistForm">
      <label for="regist-account">
        帐号：
        <input type="text" id="regist-account" v-model="registAccount" />
      </label>
      <br />
      <label for="regist-pwd">
        密码：
        <input type="password" id="regist-pwd" v-model="registPwd" />
      </label>
      <br />
      <div class="regist-submit-btn">
        <button @click="regist">注册</button>
      </div>
    </div>
  </div>
</template>
<script>
import "./index.less";
import { toggleBtn, userData, middleVue, shopcartData } from "../../services";
import { registAccount, registPwd, login } from "../../utils";
import { each } from "lodash";
export default {
  data() {
    return {
      isLoginForm: true,
      isRegistForm: false,
      loginAccount: "",
      loginPwd: "",
      registAccount: "",
      registPwd: "",
      isLoginPwdShow: false
    };
  },
  methods: {
    closeLoginRegist() {
      this.loginAccount = "";
      this.loginPwd = "";
      this.registAccount = "";
      this.registPwd = "";
      this.popup.close();
    },
    showLoginForm() {
      this.isLoginForm = true;
      this.isRegistForm = false;
      toggleBtn(this, "toggleBtn");
    },
    showRegistForm() {
      this.isLoginForm = false;
      this.isRegistForm = true;
      toggleBtn(this, "toggleBtn");
    },
    regist() {
      if (registAccount(this.registAccount) && registPwd(this.registPwd)) {
        this.$axios
          .post("regist", {
            account: this.registAccount,
            pwd: this.registPwd
          })
          .then(res => {
            this.$toast({
              message: res.data.msg,
              position: "bottom"
            });
            if (res.data.code === "2") {
              // 注册成功后直接帮用户登录，帮他登录的方式就是利用本地存储对象localStorage来存储
              userData.setUserData(this.registAccount);
              middleVue.$emit("openLoginRegist", false);
              // 在线购物车需要在登录注册成功后，查询localStorage里是否有购物车数据，将数据查询出来通过接口添加登录注册成功用户
              if (shopcartData.getShopcartData()) {
                const shopcartList = [];
                each(shopcartData.getShopcartData(), item => {
                  shopcartList.push({
                    goodsId: item.goodsId,
                    quantity: item.quantity
                  });
                });
                this.$axios
                  .post("add_shopcart", {
                    user_name: this.registAccount,
                    localShopcarts: shopcartList
                  })
                  .then(res => {
                    // 清除离线购物车数据
                    shopcartData.removeShopcartData();
                  })
                  .catch(err => console.log(err));
              }
            }
            this.registAccount = "";
            this.registPwd = "";
          })
          .catch(err => console.log(err));
      } else {
        this.$toast({
          message: "注册帐号或密码不符合规定",
          position: "bottom"
        });
      }
    },
    login() {
      if (login(this.loginAccount, this.loginPwd)) {
        this.$axios
          .post("login", {
            account: this.loginAccount,
            pwd: this.loginPwd
          })
          .then(async res => {
            if (res.data.code === "1") {
              userData.setUserData(this.loginAccount);
              middleVue.$emit("openLoginRegist", false);
              // 在线购物车需要在登录注册成功后，查询localStorage里是否有购物车数据，将数据查询出来通过接口添加登录注册成功用户
              if (shopcartData.getShopcartData()) {
                const shopcartList = [];
                each(shopcartData.getShopcartData(), item => {
                  shopcartList.push({
                    goodsId: item.goodsId,
                    quantity: item.quantity
                  });
                });
                const setShopcartResponse = await this.$axios.post(
                  "add_shopcart",
                  {
                    user_name: this.loginAccount,
                    localShopcarts: shopcartList
                  }
                );
                console.log(setShopcartResponse.data.msg);
                // 清除离线购物车数据
                shopcartData.removeShopcartData();
              }
              const shopcartListResponse = await this.$axios.get(
                "getshopcarts?account=" + this.loginAccount
              );
              // 查询当前登录用户的在线购物车数据，并将结果通知给Tabbar和Shopcart组件
              let resultQuantity = 0;
              each(shopcartListResponse.data.message, item => {
                resultQuantity += item.quantity;
              });
              middleVue.$emit("getTotalQuantity", resultQuantity);
              middleVue.$emit(
                "getShopcartList",
                shopcartListResponse.data.message
              );
            }
            this.loginAccount = "";
            this.loginPwd = "";
            this.$toast({
              message: res.data.msg,
              position: "bottom"
            });
          })
          .catch(err => console.log(err));
      } else {
        this.$toast({
          message: "帐号或密码不符合规定",
          position: "bottom"
        });
      }
    }
  },
  props: ["popup"],
  mounted() {
    toggleBtn(this, "toggleBtn");
  }
};
</script>
